package org.carl.base.dingtalk.bot.util;

import cn.hutool.http.*;
import cn.hutool.json.JSONUtil;
import org.carl.base.dingtalk.bot.model.DingTalkResult;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

public class DingTalkRebootUtil {

    /**
     * post 请求，发送给哪一个机器人
     *
     * @param reboot  机器人的token
     * @param message 发送的消息
     * @return
     */
    private static DingTalkResult sendPost(String reboot, String message) {
        HttpRequest request = HttpUtil.createPost(reboot);
        request.header(Header.CONTENT_TYPE.name(), ContentType.JSON.toString());
        request.body(message);
        HttpResponse execute = request.execute();
        String body = execute.body();
        return JSONUtil.toBean(body, DingTalkResult.class);
    }

    /**
     * 选择加签方式下的加签方法
     *
     * @param secret 密钥，机器人安全设置页面，加签一栏下面显示的SEC开头的字符串
     * @return
     */
    private static Map<String, String> dingDingSec(String secret) throws Exception {
        Long timestamp = System.currentTimeMillis();
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        String sign = URLEncoder.encode(new String(Base64.getEncoder().encodeToString(signData)), "UTF-8");
        Map<String, String> map = new HashMap();
        map.put("sign", sign);
        map.put("timestamp", timestamp.toString());
        return map;
    }

    /**
     * 加签机器人实现，这里需要注意的是：timestamp和sign需要保持一致
     *
     * @param message 要发送的信息
     * @return
     * @throws Exception
     */
    public static DingTalkResult sendBot(String webhook, String secret, String message) throws Exception {
        Map<String, String> map = dingDingSec(secret);
        String sign = map.get("sign");
        String timestamp = map.get("timestamp");
        StringBuffer stringBuffer = new StringBuffer();
        String robotUrl = stringBuffer.append(webhook).append("&timestamp=").append(timestamp).append("&sign=").append(sign).toString();
        return sendPost(robotUrl, message);
    }

    /**
     * 关键字机器人：发送消息中需要有对应的关键字才能发送成功
     *
     * @param message 封装的消息
     * @return
     * @throws Exception
     */
    public static DingTalkResult sendKeyReboot(String webhook, String message) throws Exception {
        return sendPost(webhook, message);
    }
}